package com.novellotus.iov.carvice.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.model.LatLng;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Rich on 2017/8/3.
 *
 */

public class MyUtils {

    private static boolean isLog = true;

    /**
     * 打印方法
     *
     * @param msg 打印信息
     */
    public static void logInformation(String msg) {
        if (isLog) {
            if (msg == null) {
                msg = "空";
            }
            Log.d("Rich", msg);
        }
    }

    /**
     * zh中文
     * en英语
     *
     * @return 是否是英文
     */
    public static boolean isEnglish(Context context) {
        Locale locale = context.getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        return language.endsWith("en");
    }

    /**
     * 重写Toast
     */
    private static Toast toast;

    public static void showToast(Context context, String s) {
        if (toast == null) {
            toast = Toast.makeText(context, "", Toast.LENGTH_LONG);
        }
        toast.setText(s);
        toast.show();

    }

    /**
     * @param input
     * @return 处理空值
     */
    public static String getRealValue(String input) {
        String output = "";
        if (input == null || input.equals("") || input.equals("null")) {
            output = "- -";
        } else {
            output = input;
        }
        return output;
    }


    /**
     * @param lat
     * @param lng
     * @param context GPS转高德
     * @return
     */
    public static LatLng fromGpsToAmap(double lat, double lng, Context context) {
        LatLng latLng = null;
        LatLng dPoint = new LatLng(lat, lng);
        CoordinateConverter converter = new CoordinateConverter(context);
        // CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
        // sourceLatLng待转换坐标点 DPoint类型
        // 执行转换操作
        try {
            converter.coord(dPoint);
            latLng = converter.convert();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return latLng;

    }

    /**
     * 记录当前activity
     * 用于一次清空多个activity
     */
    private static List<Activity> activityList = new ArrayList<>();

    public static void addActivity(Activity activity) {
        activityList.add(activity);
    }

    /**
     * 清除列表中的Activity
     */
    public static void clearActivity() {
        for (Activity a : activityList) {
            if (a != null) {
                a.finish();
            }
        }
        activityList.clear();
    }


    /**
     * 隐藏当前小键盘
     */
    public static void hideInput(Activity activity) {
        if (activity.getCurrentFocus() != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            IBinder iBinder = activity.getCurrentFocus().getWindowToken();
            inputMethodManager.hideSoftInputFromWindow(iBinder, InputMethodManager.HIDE_NOT_ALWAYS);
            inputMethodManager.hideSoftInputFromWindow(iBinder, 0);
        }
    }


    /**
     * 判断网络是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isAvailable();
    }

    /**
     * @param
     * @param Exception 判断是否连接超时
     */
    public static boolean isTimeOut(String Exception) {
        return Exception.contains("SocketTimeoutException");
    }

    /**
     * @param
     * @param Exception 判断是转换类型出错
     */
    public static boolean isIllegalState(String Exception) {
        return Exception.contains("IllegalStateException");
    }

    /**
     * 加载本地图片
     *
     * @param url *
     * @return
     */
    public static Bitmap getLocalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis); ///把流转化为Bitmap图片
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 手机号验证
     *
     * @param phone
     * @return 验证通过返回true
     */
    public static boolean isMobile(String phone) {
        if (phone != null && phone.length() == 11) {
            Pattern p;
            Matcher m;
            boolean b;
            p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$"); // 验证手机号
            m = p.matcher(phone);
            b = m.matches();
            return b;
        } else {
            return false;
        }
    }

    /**
     * 电话号码验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isPhone(String str) {
        if (str != null && str.length() > 6) {
            Pattern p1, p2;
            Matcher m;
            boolean b;
            p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的
            p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的
            if (str.length() > 9) {
                m = p1.matcher(str);
                b = m.matches();
            } else {
                m = p2.matcher(str);
                b = m.matches();
            }
            return b;
        } else {
            return false;
        }

    }

    /**
     * 车牌号验证
     *
     * @param plate
     * @return 验证通过返回true
     */
    public static boolean isPlate(String plate) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile("^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1,2}$");
        m = p.matcher(plate);
        b = m.matches();
        return b;
    }

    /**
     * 车牌号验证
     * <p>
     * 检查是否由中英文组成
     *
     * @return 验证通过返回true
     */
    public boolean isValid(String vin) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile("^[A-Z0-9]{17}$");
        m = p.matcher(vin);
        b = m.matches();
        return b;
    }

    /**
     * 检验VIN格式
     *
     * @param vin
     * @return
     */
    public static boolean isVin(String vin) {
        try {
            if (vin == null && isVin(vin))
                return false;
            Map<Integer, Integer> vinMapWeighting = null;
            Map<Character, Integer> vinMapValue = null;
            vinMapWeighting = new HashMap<>();
            vinMapValue = new HashMap<>();
            vinMapWeighting.put(1, 8);
            vinMapWeighting.put(2, 7);
            vinMapWeighting.put(3, 6);
            vinMapWeighting.put(4, 5);
            vinMapWeighting.put(5, 4);
            vinMapWeighting.put(6, 3);
            vinMapWeighting.put(7, 2);
            vinMapWeighting.put(8, 10);
            vinMapWeighting.put(9, 0);
            vinMapWeighting.put(10, 9);
            vinMapWeighting.put(11, 8);
            vinMapWeighting.put(12, 7);
            vinMapWeighting.put(13, 6);
            vinMapWeighting.put(14, 5);
            vinMapWeighting.put(15, 4);
            vinMapWeighting.put(16, 3);
            vinMapWeighting.put(17, 2);

            vinMapValue.put('0', 0);
            vinMapValue.put('1', 1);
            vinMapValue.put('2', 2);
            vinMapValue.put('3', 3);
            vinMapValue.put('4', 4);
            vinMapValue.put('5', 5);
            vinMapValue.put('6', 6);
            vinMapValue.put('7', 7);
            vinMapValue.put('8', 8);
            vinMapValue.put('9', 9);
            vinMapValue.put('A', 1);
            vinMapValue.put('B', 2);
            vinMapValue.put('C', 3);
            vinMapValue.put('D', 4);
            vinMapValue.put('E', 5);
            vinMapValue.put('F', 6);
            vinMapValue.put('G', 7);
            vinMapValue.put('H', 8);
            vinMapValue.put('J', 1);
            vinMapValue.put('K', 2);
            vinMapValue.put('M', 4);
            vinMapValue.put('L', 3);
            vinMapValue.put('N', 5);
            vinMapValue.put('P', 7);
            vinMapValue.put('R', 9);
            vinMapValue.put('S', 2);
            vinMapValue.put('T', 3);
            vinMapValue.put('U', 4);
            vinMapValue.put('V', 5);
            vinMapValue.put('W', 6);
            vinMapValue.put('X', 7);
            vinMapValue.put('Y', 8);
            vinMapValue.put('Z', 9);
            boolean reultFlag = false;
            String uppervin = vin.toUpperCase();
            //排除字母O、I
            if (vin == null || uppervin.indexOf("O") >= 0 || uppervin.indexOf("I") >= 0) {
                reultFlag = false;
            } else {
                //1:长度为17
                if (vin.length() == 17) {
                    char[] vinArr = uppervin.toCharArray();
                    int amount = 0;
                    for (int i = 0; i < vinArr.length; i++) {
                        //VIN码从从第一位开始，码数字的对应值×该位的加权值，计算全部17位的乘积值相加
                        amount += vinMapValue.get(vinArr[i]) * vinMapWeighting.get(i + 1);
                    }
                    //乘积值相加除以11、若余数为10，即为字母Ｘ
                    if (amount % 11 == 10) {
                        reultFlag = vinArr[8] == 'X';

                    } else {
                        //VIN码从从第一位开始，码数字的对应值×该位的加权值，
                        //计算全部17位的乘积值相加除以11，所得的余数，即为第九位校验值
                        reultFlag = amount % 11 == vinMapValue.get(vinArr[8]);
                    }
                }
                //1:长度不为17
                if (!vin.equals("") && vin.length() != 17) {
                    reultFlag = false;
                }
            }
            return reultFlag;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 验证邮箱
     */

    public static boolean isEmail(String email) {
        Pattern p;
        Matcher m;
        boolean b;
        //    p = Pattern.compile("^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$");
        p = Pattern.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{3,}$");
        m = p.matcher(email);
        b = m.matches();
        return b;
    }

    /**
     * 验证密码
     */
    public static boolean isPassword(String psw) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile("^\\w{6,32}$"); // 验证手机号
        m = p.matcher(psw);
        b = m.matches();
        return b;
    }

    /**
     * @return 根据 在线状态、充电状态、报警状态返回车辆状态
     * 0离线 1 在线 2充电 3报警
     */
    public static int carType(int online, int charge, int alarm) {
        int type;
        if (online == 1) {
            type = 1;
            if (charge != 3 && charge != 0) {
                type = 2;
            }
        } else {
            type = 0;
        }

        return type;
    }


    /**
     * @param online
     * @param charge
     * @param alarm
     * @return 0离线 1 在线 2充电 3报警1 4报警2 5报警3
     */
    public static int carDetailType(int online, int charge, int alarm) {
        int type;
        if (online == 1) {
            type = 1;
            if (charge != 3 && charge != 0) {
                type = 2;
            }
        } else {
            type = 0;
        }

        switch (alarm) {
            case 1:
                type = 3;
                break;
            case 2:
                type = 4;
                break;
            case 3:
                type = 5;
                break;
        }
        return type;
    }

    /**
     * @return 返回报警状态下图片的状态
     * 0 离线 1在线 2充电
     */
    public static int carAlarmStatueBackground(int online, int charge) {
        int type;
        if (online == 1) {
            type = 1;
            if (charge != 3 && charge != 0) {
                type = 2;
            }
        } else {
            type = 0;
        }

        return type;
    }


    /**
     * 通过反射获取状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取版本号
     *
     * @param context 上下文
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //返回版本号
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 车牌转换格式
     */
    public static String getPlateString(String plate) {
        String s = "";
        if (plate != null && plate.length() > 5) {
            StringBuilder sb = new StringBuilder(plate);
            sb.insert(2, " ");
            s = sb.toString();
        } else {
            s += "-- --";
        }
        return s;
    }

    /**
     * 将null或者空的值转为--显示
     */
    public static String getRealNumberValue(String value) {
        if (value != null && !value.equals("null") && !value.equals("") && !value.equals("-- --")) {
            BigDecimal bd = new BigDecimal(value);
            BigDecimal b2 = new BigDecimal(100);
            double mul = bd.multiply(b2).doubleValue();
            BigDecimal bd3 = new BigDecimal(mul);
            BigDecimal realValue = bd3.divide(b2).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            DecimalFormat decimalFormat = new DecimalFormat("#.##");//保留有效数字
            return decimalFormat.format(realValue);
        } else {
            return "-- --";
        }
    }

}
